package cn.itcast.bigdata.distributeLock;

import java.util.concurrent.CountDownLatch;

import org.I0Itec.zkclient.IZkDataListener;

public class ZookeeperDistributeLock extends ZookeeperAbstractLock {
	
	private CountDownLatch countDownLatch =new CountDownLatch(1);
		
	@Override
	protected boolean tryLock() {
		try {
			zkClient.createEphemeral(PATH);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	protected void waitLock() {
		
		IZkDataListener zkDataListener = new IZkDataListener() {
			@Override
			public void handleDataDeleted(String path) throws Exception {
				if (null !=countDownLatch) {
					//唤醒当前被等待的线程
					countDownLatch.countDown();
					System.out.println("删除节点");
				}
			}
			@Override
			public void handleDataChange(String path, Object data) throws Exception {
				
			}
		};
		
		zkClient.subscribeDataChanges(PATH,zkDataListener);
		
		if (zkClient.exists(PATH)) {
			countDownLatch = new CountDownLatch(1);
			try {
				countDownLatch.await();
			} catch (Exception e) {
				
			}
		}
		zkClient.unsubscribeDataChanges(PATH,zkDataListener);
		
	}

}
